package com.zanglikun.rocketmq.batch;

import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.common.message.MessageExt;

import java.util.List;

/**
 * @Author: zanglikun
 * @Date: 2022/3/31 20:41
 * @Description: 批量消息消费者，与普通消费者代码无异
 */
public class BatchConsumer {
    public static void main(String[] args) throws Exception {
        // todo 1 创建消费者，同时指定消费组
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("group1");
        // todo 2 指定NameServer
        consumer.setNamesrvAddr("192.168.253.128:9876;192.168.253.129:9876");
        // todo 3 订阅主题
        consumer.subscribe("Batch", "*");
        // todo 4 设置回调函数，以处理消息
        consumer.registerMessageListener(new MessageListenerConcurrently() {
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> list, ConsumeConcurrentlyContext consumeConcurrentlyContext) {
                //System.out.println(list);
                list.forEach(messageExt -> {
                    System.out.println("消费的内容：" + new String(messageExt.getBody()));
                });
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            }
        });
        // todo 5 启动消费者
        consumer.start();
        System.out.println("消费者启动完成！");
    }
}
